 #include "loginwidget.h"


LoginWidget::LoginWidget(QWidget *parent) : QWidget(parent)
{
    qsrand(QTime::currentTime().msec());
    this->resize(200,700);
    this->con=MyControl::getInstance();
    this->initUI();
}


//验证码函数
//生成随机验证码字符串
QString generateRandomCode(int len)
{
   const QString possibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
   QString randomString;
   for(int i=0;i<len;i++)
   {
       int index=qrand()%possibleCharacters.length();
       randomString.push_back(possibleCharacters.at(index));
   }
   return randomString;
}
//生成验证码图片
QPixmap  *generateCaptchaImage(const QString &code, int width, int height)
{
    QPixmap *pixmap=new QPixmap(width, height);
    pixmap->fill(Qt::white);

    QPainter painter(pixmap);
    painter.setFont(QFont("Arial", 15));

    //绘制验证码字符串
    for(int i=0;i<code.length();i++)
    {
        QColor color(qrand()%256,qrand()%256,qrand()%256);
        painter.setPen(color);
        int x = i * (width / code.length()) + (qrand() % 10);
        int y = height /2 + (qrand() % 10);
        painter.drawText(x,y,QString(code[i]));
    }

    //添加干扰线
    for (int i = 0; i < 5; ++i) {
           QColor color(qrand() % 256, qrand() % 256, qrand() % 256);
           painter.setPen(color);
           int x1 = qrand() % width;
           int y1 = qrand() % height;
           int x2 = qrand() % width;
           int y2 = qrand() % height;
           painter.drawLine(x1, y1, x2, y2);
       }


    painter.end();
    return pixmap;
}



void LoginWidget::initUI()
{
    this->title=new QLabel("登录界面",this);
    this->deviceNum=new QLabel("设备编号",this);
    this->policeNum=new QLabel("警员编号",this);
    this->password=new QLabel("密    码",this);
    this->verifeCode=new QLabel("验 证 码",this);

    //this->deviceNum_edit=new QLineEdit();
    this->policeNum_edit=new QLineEdit();
    this->password_edit=new QLineEdit();
    this->password_edit->setMaxLength(10);
    this->verifeCode_edit=new QLineEdit();
    this->device_box=new QComboBox();
    this->password_box=new QPushButton(QIcon("../image_tool/visibility-button.png"),"",this);

    this->ensure=new QPushButton("确定");
    this->cancel=new QPushButton("取消");


    this->Codepicture=new QLabel();
    this->image=new QPixmap();
    //绘制验证码
    this->createCode();
    this->Codepicture->setPixmap(*image);

    this->layout_H1=new QHBoxLayout();
    this->layout_H2=new QHBoxLayout();
    this->layout_H3=new QHBoxLayout();
    this->layout_H4=new QHBoxLayout();
    this->layout_H5=new QHBoxLayout();
    this->layout_H6=new QHBoxLayout();


    this->layout_V=new QVBoxLayout();


    QFont font;
    font.setPixelSize(30);
    font.setBold(true);//字体加粗
    title->setFont(font);
    deviceNum->setFont(font);
    policeNum->setFont(font);
    password->setFont(font);
    verifeCode->setFont(font);
    policeNum_edit->setFont(font);
    password_edit->setFont(font);
    verifeCode_edit->setFont(font);
    device_box->setFont(font);
    password_box->setFont(font);
    ensure->setFont(font);
    cancel->setFont(font);



    this->layout_H1->addWidget(title);
    this->layout_H2->addWidget(deviceNum);
    this->layout_H2->addWidget(device_box);
    this->layout_H3->addWidget(policeNum);
    this->layout_H3->addWidget(policeNum_edit);
    this->layout_H4->addWidget(password);
    this->layout_H4->addWidget(password_edit);
    this->layout_H4->addWidget(password_box);
    this->layout_H5->addWidget(verifeCode);
    this->layout_H5->addWidget(verifeCode_edit);
    this->layout_H5->addWidget(Codepicture);
    this->layout_H6->addWidget(ensure);
    this->layout_H6->addWidget(cancel);

    this->layout_V->addLayout(layout_H1);
    this->layout_V->addLayout(layout_H2);
    this->layout_V->addLayout(layout_H3);
    this->layout_V->addLayout(layout_H4);
    this->layout_V->addLayout(layout_H5);
    this->layout_V->addLayout(layout_H6);



    this->layout_H1->addWidget(title);
    this->layout_H1->setAlignment(Qt::AlignCenter);  // 标题居中
    this->layout_H1->setContentsMargins(100,0,0,0);


    layout_V->setSpacing(10);  // 调整垂直间距为 10，可根据实际情况修改
    layout_V->setContentsMargins(100, 100, 100, 200);  // 设置整体边距




    QSizePolicy passwordBoxPolicy = password_box->sizePolicy();
    passwordBoxPolicy.setHorizontalStretch(1); // 减小下拉框的水平拉伸因子
    password_box->setSizePolicy(passwordBoxPolicy);
    password_box->setMaximumWidth(25); // 设置下拉框的最大宽度




    int horizontalSpacing = 5; // 可根据需要调整
    layout_H1->setSpacing(horizontalSpacing);
    layout_H2->setSpacing(horizontalSpacing);
    layout_H3->setSpacing(horizontalSpacing);
    layout_H4->setSpacing(horizontalSpacing);
    layout_H5->setSpacing(horizontalSpacing);
    layout_H6->setSpacing(horizontalSpacing);

    //规定密码和警员编号为数字或者英文
    QRegExp regExp2("^[a-zA-Z0-9]{6,10}$"); // 密码最小 6 位
    QRegExpValidator *validator1 = new QRegExpValidator(regExp2, policeNum_edit);
    QRegExpValidator *validator2 = new QRegExpValidator(regExp2, password_edit);
    policeNum_edit->setValidator(validator1);
    password_edit->setValidator(validator2);

    //密码框用密文显示
     password_edit->setEchoMode(QLineEdit::Password);


     //编辑框样式表
     QString lineEditStyle = "QLineEdit {"
                                "  border: 2px solid #ccc;"  // 边框样式，2px 宽，灰色
                                "  border-radius: 5px;"      // 圆角效果，半径为 5px
                                "  padding: 5px;"            // 内边距为 5px
                                "  background-color: #f9f9f9;" // 背景颜色为浅灰色
                                "  color: #333;"              // 字体颜色为深灰色
                                "}"
                                "QLineEdit:focus {"
                                "  border-color: #007BFF;"    // 聚焦时边框颜色变为蓝色
                                "}";


     device_box->setStyleSheet(lineEditStyle);
     policeNum_edit->setStyleSheet(lineEditStyle);
     password_edit->setStyleSheet(lineEditStyle);
     verifeCode_edit->setStyleSheet(lineEditStyle);


    this->setLayout(layout_V);

     //设备编号选择
     QList<QCameraInfo>camers=QCameraInfo::availableCameras();
     QList<QCameraInfo>::iterator iter=camers.begin();
     int index=0;
     while(iter!=camers.end())
     {
         QString str=camers[index++].description();
         qDebug()<<str;
         this->device_box->addItem(str);
         iter++;
     }


     Codepicture->installEventFilter(this);


    connect(password_box,&QPushButton::clicked,this,&LoginWidget::passwdChange);
    connect(ensure,&QPushButton::clicked,this,&LoginWidget::isLoginFinished);
    connect(cancel,&QPushButton::clicked,this,&LoginWidget::sendCancelClicked);


}

void LoginWidget::createCode()
{
    code=generateRandomCode(4);
    image=generateCaptchaImage(code,120,40);

}
//ed5
QString LoginWidget::md5Encrypt(const QString &passwd)
{
      QCryptographicHash md5(QCryptographicHash::Md5);
      md5.addData(passwd.toLocal8Bit());
      return md5.result().toHex();
}
//明文密文的转换
void LoginWidget::passwdChange()
{
    if(password_edit->echoMode()==QLineEdit::Password)
    {
        password_edit->setEchoMode(QLineEdit::Normal);
        this->password_box->setIcon(QIcon("../image_tool/eye.png"));
    }
    else {
        password_edit->setEchoMode(QLineEdit::Password);
        this->password_box->setIcon(QIcon("../image_tool/visibility-button.png"));
    }

}
//验证码刷新
void LoginWidget::refreshCaptcha()
{
    this->createCode();
    Codepicture->setPixmap(*image); // 确保图片被更新显示
}
//登陆
void LoginWidget::isLoginFinished()
{
    if(password_edit->text().size()&&policeNum_edit->text().size()||verifeCode_edit->text().size())
    {
        if(password_edit->text().size()<6||policeNum_edit->text().size()<6)
        {
            QMessageBox::warning(this,"警告","账号或者密码不能小于6位");
            policeNum_edit->clear();
            password_edit->clear();
            return;
        }
        User *user;
        this->model=this->con->getModel("user_info");
        QString sql=QString("select * from user_info where user_info.username='%1' and user_info.password='%2'").arg(policeNum_edit->text(),md5Encrypt(password_edit->text()));
        user=this->model->getUserInfo((char *)sql.toStdString().c_str());


        qDebug()<<user->getUser_id()<<user->getUsername()<<user->getPassword();
        qDebug()<<md5Encrypt(password_edit->text());


         if(user->getUsername()==policeNum_edit->text()&&user->getPassword()==md5Encrypt(password_edit->text())&&verifeCode_edit->text().toLower() == code.toLower())
         {
             QMessageBox::information(this,"提示","登陆成功");
             QString sql=QString("SELECT user_id from user_info WHERE user_info.username='%1';").arg(policeNum_edit->text());

             id=this->model->selectUserId((char *)sql.toStdString().c_str());//把登录者的id记录下来，方便后面使用

             this->police_num=this->policeNum_edit->text();
             //把信息写入数据库
             QDateTime currentDateTime = QDateTime::currentDateTime();
             qDebug()<<currentDateTime.toString();
             QString timeStr = currentDateTime.toString("yyyy-MM-dd-hh-mm-ss");
             this->model=this->con->getModel("operation_log");
             if(model==nullptr)
             {
                 qDebug()<<"model为空";
             }
             //获取设备编号

              sql= QString("insert into operation_log (user_id,operation_type,operation_time,log_device) values (%1,'%2','%3','%4');")
                     .arg(id)
                     .arg("登录")
                     .arg(timeStr)
                     .arg(this->device_box->currentText());
               qDebug()<<sql;
             Any ret=this->model->sqlInstruct((char *)sql.toStdString().c_str());




             //把信息清空
             this->password_edit->clear();
             this->policeNum_edit->clear();
             this->verifeCode_edit->clear();


             emit LoginToRet(index);//这里不应该写进入主窗口，只有登录操作才行，如果是其他窗口未登录需要发送不同的信号

             return;
         }
         else
         {
             if((user->getUsername()!=policeNum_edit->text()||user->getPassword()!=md5Encrypt(password_edit->text()))&&verifeCode_edit->text()==code)
             {
             QMessageBox::information(this,"提示","登陆失败,账号或者密码错误");
             policeNum_edit->clear();
             password_edit->clear();
             }
             else
             {
                 QMessageBox::information(this,"提示","登陆失败,验证码错误");
             }
         }
    }
    else
    {
        QMessageBox::warning(this,"警告","账号或者密码不为空");
    }




}

void LoginWidget::sendCancelClicked()
{
    this->password_edit->clear();
    this->policeNum_edit->clear();
    this->verifeCode_edit->clear();
     emit RetToMain();
}

QString LoginWidget::getPolice_num() const
{
    return police_num;
}

void LoginWidget::setPolice_num(const QString &value)
{
    police_num = value;
}

int LoginWidget::getIndex() const
{
    return index;
}

void LoginWidget::setIndex(int value)
{
    index = value;
}

int LoginWidget::getUser_id() const
{
    return user_id;
}

void LoginWidget::setUser_id(int value)
{
    user_id = value;
}


//事件过滤
bool LoginWidget::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == Codepicture && event->type() == QEvent::MouseButtonPress) {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
            if (mouseEvent->button() == Qt::LeftButton) {
                refreshCaptcha();
                return true;
            }
        }
        return QWidget::eventFilter(obj, event);
}






